package com.smartshopping.iu;

import java.io.IOException;
import java.nio.channels.Selector;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.smartshopping.model.*;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class BillActivity extends Activity {

	private DataBaseHelper myDbHelper;
	private BillItem bill;
	private Intent resultData;
			
	private final int ITEM_BUY = Color.BLACK;
	private final int ITEM_DEL = Color.RED;
	private final int PRICE_BLUE = Color.BLUE;
	
	private String sql = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bill);
		
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		bill = new BillItem(extras.getParcelableArrayList("list"),Integer.parseInt(extras.getString("coopID")),Integer.parseInt(extras.getString("marketID")));
		connectionDatabase();
		
		coutSum();
		createTheHeader();
		createTheListItem();
		createFooter();
	}

	public void connectionDatabase()
	{
		myDbHelper = new DataBaseHelper(this);
		try 
		{
			myDbHelper.createDataBase(this);
			myDbHelper.openDataBase();
		} catch (IOException ioe) 
		{
		 		throw new Error("Unable to create database");
		}
	}
	
	//Create the title of the bill
	public void createTheHeader()
	{
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		SQLiteDatabase mdb = myDbHelper.getReadableDatabase();
		final String sql = "select * from market where market._id = " + Integer.toString(bill.getMarketId());
		Cursor mCursor = mdb.rawQuery(sql, null); 	
		if(mCursor.moveToFirst())
			((TextView)findViewById(R.id.bill_market)).setText("Siêu thị : " + mCursor.getString(1));
		mCursor.close();
		final String sql1 = "select * from coop where coop._id = " + Integer.toString(bill.getCoopId());
		mCursor = mdb.rawQuery(sql1, null); 	
		if(mCursor.moveToFirst())
			((TextView)findViewById(R.id.bill_coop)).setText("Thuộc hệ thống : " + mCursor.getString(1));
		mCursor.close();
		mdb.close();
	}
	
	public void createTheListItem()
	{
		LinearLayout layout = (LinearLayout) findViewById(R.id.bill_LinearLayout);
		layout.setOrientation(LinearLayout.VERTICAL);  //Can also be done in xml by android:orientation="vertical"
		for (int index = 0; index < bill.getNumberItem(); index++) 
		{
			final int in = index;
			System.out.println(in);
		    LinearLayout row = new LinearLayout(this);
		    row.setOrientation(LinearLayout.HORIZONTAL);
		    row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		    LinearLayout row1 = new LinearLayout(this);
		    row1.setOrientation(LinearLayout.HORIZONTAL);
		    row1.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		    
		    //Name of good
		    TextView textviewName = new TextView(this);
		    textviewName.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		    textviewName.setText(bill.getList().get(index).getName() + " ");
		    textviewName.setId(1 + (index * 6));
		    row.addView(textviewName);
		    
		    
		    
		    //Sub imageButton
		   	ImageButton imageButtonSub = new ImageButton(this);
		    imageButtonSub.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		    imageButtonSub.setId(2 +(index * 6));
		    imageButtonSub.setBackgroundResource(R.color.selector_sub);
		    row1.addView(imageButtonSub);
		    
		    //Number of item buy
		    TextView textviewTotal = new TextView(this);
		    textviewTotal.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		    textviewTotal.setText("SL : " + Integer.toString(bill.getList().get(index).getAmount()));
		    textviewTotal.setId(3 +(index * 6));
		    textviewTotal.setTextColor(ITEM_BUY);
		    row1.addView(textviewTotal);
		    
		    imageButtonSub.setOnClickListener(new View.OnClickListener() {
		        @Override
		        public void onClick(View v) {
		        	if (bill.getList().get(in).getAmount() > 0)
		        		bill.getList().get(in).setAmount(bill.getList().get(in).getAmount() - 1);
		        	if (bill.getList().get(in).getAmount() == 0)
		        		((TextView)findViewById(1 +(in * 6))).setTextColor(ITEM_DEL);
		        	((TextView)findViewById(3 +(in * 6))).setText("SL : " + Integer.toString(bill.getList().get(in).getAmount()));
		        	((TextView)findViewById(6 +(in * 6))).setText("Tổng giá: " + Integer.toString(bill.getList().get(in).getAmount() * bill.getList().get(in).getPrice()));
		        	coutSum();
		        }
		    });
		    
		    //Add imageButton
		    ImageButton imageButtonAdd = new ImageButton(this);
		    imageButtonAdd.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		    imageButtonAdd.setId(4 +(index * 6));
		    imageButtonAdd.setBackgroundResource(R.color.selector_plus);
		    row1.addView(imageButtonAdd);
		    imageButtonAdd.setOnClickListener(new View.OnClickListener() {
		        @Override
		        public void onClick(View v) {
		        	bill.getList().get(in).setAmount(bill.getList().get(in).getAmount() + 1);
		        	if (bill.getList().get(in).getAmount() == 1)
		        		((TextView)findViewById(1 +(in * 6))).setTextColor(ITEM_BUY);
		        	((TextView)findViewById(3 +(in * 6))).setText("SL : " + Integer.toString(bill.getList().get(in).getAmount()));
		        	((TextView)findViewById(6 +(in * 6))).setText("Tổng giá: " + Integer.toString(bill.getList().get(in).getAmount() * bill.getList().get(in).getPrice()));
		        	coutSum();
		        }
		    });
		    
		  //Del imageButton
		    ImageButton imageButtonDel = new ImageButton(this);
		    imageButtonDel.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		    imageButtonDel.setId(5 +(index * 6));
		    imageButtonDel.setBackgroundResource(R.color.selector_del);
		    row1.addView(imageButtonDel);
		    imageButtonDel.setOnClickListener(new View.OnClickListener() {
		        @Override
		        public void onClick(View v) {
		        	bill.getList().get(in).setAmount(0);
		        	((TextView)findViewById(1 +(in * 6))).setTextColor(ITEM_DEL);
		        	((TextView)findViewById(3 +(in * 6))).setText("SL : " + Integer.toString(bill.getList().get(in).getAmount()));
		        	((TextView)findViewById(6 +(in * 6))).setText("Tổng giá: " + Integer.toString(bill.getList().get(in).getAmount() * bill.getList().get(in).getPrice()));
		        	coutSum();
		        }
		    });
		    
		    //Price
		    TextView textviewSum = new TextView(this);
		    textviewSum.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		    textviewSum.setText("Tổng giá: " + Integer.toString(bill.getList().get(index).getAmount() * bill.getList().get(index).getPrice()));
		    textviewSum.setId(6 + (index * 6));
		    textviewSum.setTextColor(PRICE_BLUE);
		    row1.addView(textviewSum);
		    
		    layout.addView(row);
		    layout.addView(row1);
		}
	}
	
	//Count the total price
	public void coutSum()
	{
		int sum = 0;
		for (int i = 0; i < bill.getNumberItem(); i++)
		{
			sum += bill.getList().get(i).getAmount() * bill.getList().get(i).getPrice();
			System.out.println("Price : " + bill.getList().get(i).getPrice());
		}
		((TextView)findViewById(R.id.bill_sum)).setText("Total price : " + Integer.toString(sum));
	}
	
	//Create button save and back to buy
	public void createFooter()
	{
		((ImageButton)findViewById(R.id.bill_save_bill)).setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	if (bill.getNumberItem() > 0)
	        		askToSave();
	        }
	    });
		((ImageButton)findViewById(R.id.bill_back)).setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	resultData = new Intent();
	        	bill.deleteItemNotBuy();
	    		resultData.putParcelableArrayListExtra("list",bill.getList());
	    		setResult(Activity.RESULT_OK, resultData);
	        	finish();
	        }
	    });
	}
	
	//Ask the customer want to save the bill or not
	private void askToSave()
	{
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
		        switch (which){
		        case DialogInterface.BUTTON_POSITIVE:
		        	saveTheBill();
		            break;

		        case DialogInterface.BUTTON_NEGATIVE:
		            break;
		        }
		    }
		};

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Bạn có chắc là muốn lưu lại hóa đơn này không ?").setPositiveButton("Có", dialogClickListener)
		    .setNegativeButton("Không", dialogClickListener).show();
	}
	
	private void saveTheBill()
	{
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		String dateTest = dateFormat.format(date);
		String note = ((EditText)findViewById(R.id.bill_editText_note)).getText().toString();
		SQLiteDatabase mdbWrite = myDbHelper.getWritableDatabase();
		sql = "Insert into bill  (_id, Date, CoopID, MarketID, Note) values (null,'"
						+ dateTest + "','"
						+ Integer.toString(bill.getCoopId())  + "','"
						+ Integer.toString(bill.getMarketId()) + "','"
						+ note + "')";
		System.out.println(sql);
		mdbWrite.execSQL(sql); 	
		
		sql = "select * from bill order by _id DESC";
		System.out.println(sql);
		SQLiteDatabase mdbReader = myDbHelper.getReadableDatabase();
		Cursor mCursor = mdbReader.rawQuery(sql, null); 
		
		int billID = 0;
		if(mCursor.moveToFirst())
			billID = mCursor.getInt(0);
		for(int in = 0; in < bill.getList().size(); in++)
		{
			sql = "Insert into billdetail  (_id, BillID, ItemID, Amount, TypeID, Price, Name) values (null,'"
					+ Integer.toString(billID)  + "','"
					+ Integer.toString(bill.getList().get(in).getId()) + "','"
					+ Integer.toString(bill.getList().get(in).getAmount()) + "','"
					+ Integer.toString(bill.getList().get(in).getTypeId()) + "','"
					+ Integer.toString(bill.getList().get(in).getPrice()) + "','"
					+ bill.getList().get(in).getName() + "')";
			System.out.println(sql);
			mdbWrite.execSQL(sql);
		}
		mCursor.close();
		mdbWrite.close();
		mdbReader.close();
		//Return the value to show that bill have saved
		resultData = new Intent();
		resultData.putExtra("saved","yes");
		setResult(Activity.RESULT_OK, resultData);
    	finish();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.bill, menu);
		return true;
	}

}
